import { _decorator, Component, Node, Label, instantiate, isValid } from 'cc';
import { TableInfoItem } from './TableInfoItem';
import { UserMgr } from './UserMgr';
import { SubGameMgr } from './SubGameMgr';
const { ccclass, property } = _decorator;

@ccclass('TableInfoList')
export class TableInfoList extends Component {
    @property(Node)
    contentRoot: Node;

    @property(Node)
    tips: Node;

    private _itemPrefab: Node;

    async start() {
        this.contentRoot.active = false;
        this.tips.active = true;
        this._itemPrefab = this.contentRoot.children[0];
        this._itemPrefab.removeFromParent();
        this.refreshTableList();

        this.schedule(() => {
            this.refreshTableList();
        }, 3);
    }

    async refreshTableList() {
        let ret = await UserMgr.inst.rpc_GetTableList(SubGameMgr.current.id);
        if (!ret.isSucc) {
            return;
        }
        if (!this.isValid) {
            return;
        }
        let tables = ret.res.subWorlds;
        if (tables) {
            this.contentRoot.children.forEach(v => {
                v.active = false;
            });
            this.tips.active = false;
            this.contentRoot.active = true;
            for (let i = 0; i < tables.length; ++i) {
                let node = this.contentRoot.children[i];
                if (!node) {
                    node = instantiate(this._itemPrefab);
                    this.contentRoot.addChild(node);
                }

                node.active = true;

                let cache = tables[i];
                let item = node.getComponent(TableInfoItem);

                item.lblTableId.string = cache.displayId;
                item.lblName.string = cache.name;
                item.lblPlayerNum.string = cache.playerNum + '/' + cache.maxPlayerNum;

                let maxSpectatorNum = cache.maxUserNum - cache.maxPlayerNum;
                let spectatorNum = cache.userNum - cache.playerNum;
                item.lblSpectatorNum.string = spectatorNum + '/' + maxSpectatorNum;
            }
        }
    }

    update(deltaTime: number) {

    }
}

